import ttkbootstrap as ttk
from ttkbootstrap.constants import *


class FormBuilder:
    def __init__(self, parent, data=None):
        self.parent = parent
        self.widgets = []
        self.data = data if data else {}

    def text(self, field_name, label_text):
        label = ttk.Label(self.parent, text=label_text)
        label.pack(pady=5)
        entry = ttk.Entry(self.parent)
        entry.pack(pady=5)
        self.widgets.append((field_name, entry))
        if field_name in self.data:
            entry.insert(0, self.data[field_name])
        return self

    def default(self, value):
        if self.widgets:
            _, last_entry = self.widgets[-1]
            if last_entry.get() == "":
                last_entry.insert(0, value)
        return self

    def get_values(self):
        values = {}
        for field_name, entry in self.widgets:
            values[field_name] = entry.get()
        return values

    def add_submit_button(self, handler, text="提交", color="primary"):
        def on_submit():
            values = self.get_values()
            handler(values)

        submit_button = ttk.Button(self.parent, text=text, command=on_submit, bootstyle=color)
        submit_button.pack(pady=20)


# 继承 FormBuilder 类的新表单类
class CustomForm(FormBuilder):
    def __init__(self, parent, data=None):
        super().__init__(parent, data)
        self.setup_form()

    def setup_form(self):
        # 定义表单字段
        self.text('name', '姓名').default('默认姓名')
        self.text('age', '年龄').default('18')
        # 添加提交按钮并指定处理函数
        self.add_submit_button(self.handle_submit, '提交表单', SUCCESS)

    def handle_submit(self, values):
        print("提交的数据：", values)
        # 这里可以添加更多的业务逻辑，比如数据验证、保存到数据库等


# 创建主窗口
root = ttk.Window(themename="flatly")
root.title("自定义表单")

# 编辑数据
data = {"name": "张三", "age": "20"}

# 创建自定义表单实例
form = CustomForm(root, data)

# 运行主循环
root.mainloop()